<template>
<div class="page-container">
    <!-- 顶部标题 -->
    <div class="header-title">
      <h1>成都市市场监督管理局教育培训中心</h1>
    </div>
      <div class="forget-password">
    <el-form ref="forgetForm" :model="forgetForm" :rules="forgetRules" class="forget-form">
      <h3 class="title">{{title}}</h3>
      <el-form-item prop="phonenumber">
        <el-input
          v-model="forgetForm.phonenumber"
          type="text"
          auto-complete="off"
          placeholder="请输入邮箱/手机号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>

      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="forgetForm.code"
          auto-complete="off"
          placeholder="请输入验证码"
          style="width: 63%"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="code-btn-container">
          <el-button
            class="code-btn"
            :disabled="codeBtnDisabled"
            @click="sendCode"
          >
            {{codeBtnText}}
          </el-button>
        </div>
      </el-form-item>

      <el-form-item prop="newPassword" v-if="showPassword">
        <el-input
          v-model="forgetForm.newPassword"
          type="password"
          auto-complete="off"
          placeholder="请输入新密码">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>

      <el-form-item prop="confirmPassword" v-if="showPassword">
        <el-input
          v-model="forgetForm.confirmPassword"
          type="password"
          auto-complete="off"
          placeholder="请确认新密码">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>

      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:70%;"
          @click.native.prevent="handleForget"
        >
          <span v-if="!loading">重置密码</span>
          <span v-else>提交中...</span>
        </el-button>
        <div style="float: right; margin-top: 15px;margin-left: 20px;">
          <router-link class="link-type" :to="'/login'">返回登录</router-link>
        </div>
      </el-form-item>
    </el-form>
    <div class="el-register-footer">
      <span></span>
    </div>
  </div>
</div>
</template>

<script>
import { getCodeImg, sendCode, forgetPassword } from "@/api/login"

export default {
  name: "ForgetPassword",
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.forgetForm.newPassword !== value) {
        callback(new Error("两次输入的密码不一致"))
      } else {
        callback()
      }
    }
    return {
      title: "忘记密码",
      codeUrl: "",
      forgetForm: {
        phonenumber: "",
        code: "",
        newPassword: "",
        confirmPassword: "",
        uuid: ""
      },
      forgetRules: {
        phonenumber: [
          { required: true, trigger: "blur", message: "请输入手机号" },
          { pattern: /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])|(?:\d{11})$/,
            message: "请输入正确的11位手机号",
            trigger: "blur"
          }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
        newPassword: [
          { required: true, trigger: "blur", message: "请输入新密码" },
          { min: 6, max: 20, message: "密码长度需6-20位", trigger: "blur" },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, trigger: "blur", message: "请再次输入新密码" },
          { validator: equalToPassword, trigger: "blur" }
        ]
      },
      loading: false,
      captchaEnabled: true,
      codeBtnText: "获取验证码",
      codeBtnDisabled: false,
      countdown: 60,
      showPassword: true,
      uuid:"",
    }
  },
  created() {
    // this.getCode()
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img
          this.forgetForm.uuid = res.uuid
        }
      })
    },
    // 生成UUID
    generateUuid() {
      this.forgetForm.uuid =  'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = Math.random() * 16 | 0
        const v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
      })
      console.log('生成的UUID:', this.uuid)
    },
    sendCode() {
      // 验证账号格式
      const phonenumber = this.forgetForm.phonenumber.trim()
      if (!phonenumber) {
        this.$message.error("请先输入手机号")
        return
      }

      // 发送验证码请求
      this.generateUuid();
      sendCode(phonenumber, this.forgetForm.uuid ).then(res => {
        this.$message.success("验证码已发送，请注意查收")
        this.startCountdown()
      }).catch(() => {
        this.$message.error("验证码发送失败，请稍后重试")
      })
    },
    startCountdown() {
      this.codeBtnDisabled = true
      const timer = setInterval(() => {
        if (this.countdown <= 0) {
          clearInterval(timer)
          this.codeBtnText = "获取验证码"
          this.codeBtnDisabled = false
          this.countdown = 60
        } else {
          this.codeBtnText = `${this.countdown}秒后重新获取`
          this.countdown--
        }
      }, 1000)
    },
    handleForget() {
      this.$refs.forgetForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 提交新密码
            forgetPassword(this.forgetForm.phonenumber,this.forgetForm.code,this.forgetForm.newPassword,this.forgetForm.uuid).then(res => {
              this.$alert("密码重置成功，请使用新密码登录", "提示", {
                type: "success"
              }).then(() => {
                this.$router.push("/login")
              })
            }).catch(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.page-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  background-color: #1f2d3d;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
  padding: 20px;
}

.header-title {
  width: 100%;
  text-align: center;
  margin-bottom: 30px;
  color: white;

  h1 {
    font-size: 28px;
    font-weight: bold;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
    color: #fff;
    margin: 0;
    padding: 15px 0;
    letter-spacing: 2px;
  }
}
.forget-password {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.forget-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }

  .code-btn-container {
    width: 33%;
    height: 38px;
    float: right;
    display: flex;
    align-items: center;

    .code-btn {
      width: 100%;
      height: 38px;
      padding: 0 12px;
    }
  }

  .el-form-item__content {
    display: flex;
    align-items: center;
  }
}

.el-register-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;

  span {
    background: rgba(0, 0, 0, 0.3);
    padding: 5px 10px;
    border-radius: 4px;
  }
}
</style>
